<?php

namespace teach\controllers;

use teach\components\WeChat;
use teach\components\WeChatRefund;
use teach\service\SendWechatMessage;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class WechatController extends Controller
{
    public $enableCsrfValidation= false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 解码用户手机号并记录入库
     * @return \yii\web\Response
     */
    public function actionPhone()
    {
        $request = Yii::$app->request;
        //code -> sessionKey
        $code = $request->post('code');
        $encryptedData = $request->post('encryptedData');
        $iv = $request->post('iv');
        $uid = $request->post('uid');

        $msg = '';
        $flag = false;
        if (!$code) {
            $msg = 'code 不能为空';
        } elseif (!$encryptedData) {
            $msg = 'encryptedData 不能为空';
        } elseif (!$iv) {
            $msg = 'iv 不能为空';
        } elseif (!$uid) {
            $msg = 'uid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $WetChat = new WeChat();
            $sessionKeyItem = $WetChat->getSessionKey($code);
            if ($sessionKeyItem) {
                $error = isset($sessionKeyItem['errcode']) ? $sessionKeyItem['errcode'] : false;
                if ($error) {
                    $jsonData = ResponseHelper::buildJsonData(400, 'sessionKey获取失败.');
                    return $this->asJson($jsonData);
                }
                $sessionKey = $sessionKeyItem['session_key'];
                $data = $WetChat->getDecryptData($sessionKey, $iv, $encryptedData);
                if ($data && $data['result']) {
                    $WetChatService = new \teach\service\WeChat();
                    $where = " id = {$uid} ";
                    $map = " phone = {$data['data']['phoneNumber']} ";
                    $res = $WetChatService->wetChatPhone($map, $where);
                    if ($res) {
                        $jsonData = ResponseHelper::buildJsonData(200, '成功');
                    } else {
                        $jsonData = ResponseHelper::buildJsonData(400, '记录失败');
                    }

                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '解码失败');
                }
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, 'sessionKye获取失败');
            }

        }
        return $this->asJson($jsonData);
    }

    public function actionMsgSome()
    {
        //需要同时申请公众号模板消息,再封装处理
        $SendWeChatMessage = new SendWechatMessage();
        $WeChat = new WeChat();
        $openid_developer = "oLAZ75aa9tYmJB3mIaLzMfOBcAkA";
//        $openid_developer = "oLAZ75S1P1kkMF05nK03WaObf_J8";
        $des  = "测试统一消息服务";
        $project_name = "测试统一消息服务";
        $tip = "测试看看";
        $address = "teach/wechat/msg-some";
        $status_developer = $WeChat->sendMsgSome($SendWeChatMessage->developerSame($openid_developer, '', $des, $project_name, $tip, $address));
        var_dump($status_developer);
//        $redis = Yii::$app->redis;
//        while (true) {
//            $openid_developer = "oLAZ75aa9tYmJB3mIaLzMfOBcAkA";
//            $des  = "测试统一消息服务";
//            $project_name = "测试统一消息服务";
//            $tip = "测试看看";
//            $address = "teach/wechat/msg-some";
//            $formid_developer = $redis->rpop("formid_{$openid_developer}");
//            $status_developer = $WeChat->sendMsgSome($SendWeChatMessage->developerSame($openid_developer, $formid_developer, $des, $project_name, $tip, $address));
//            if ($status_developer['errcode'] == 0 || $status_developer == false) {
//                break;
//            } else {
//                var_dump($status_developer);
//            }
//        }
    }

    /**
     * 退款
     * @return \yii\web\Response
     */
    public function actionRefund()
    {
        $appid = Yii::$app->params['serviceNum'][10000]['appid']; //公众号appid
        $mch_id = Yii::$app->params['serviceNum']['mchId']; //服务商号
        $sub_mch_id = Yii::$app->params['serviceNum'][10000]['sub_mch_id'];
        $key = Yii::$app->params['serviceNum']['md5Key']; //支付密匙设置
        $transaction_id = '4200000291201905291448896202'; //微信订单号
        $out_refund_no = 'Refund' . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);; //退款订单号
        $total_fee = 0.04; //订单金额
        $refund_fee = 0.04; //申请退款金额
        $WeChatRefund = new WeChatRefund($appid, $mch_id, $key, $sub_mch_id, $transaction_id, $out_refund_no, $total_fee, $refund_fee);
        $result = $WeChatRefund->refund();
        return $this->asJson($result);

    }
}